package org.dragonnova.lamp;

import android.util.Log;

import org.dragonnova.lamp.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * Created by hucn on 2016/10/26.
 * Description: 保存Lamp状态的类
 */
public class TapManager {

    public static final String TAG = TapManager.class.getSimpleName();

    private final TreeMap<Integer, Tap> taps = new TreeMap<>();

    public synchronized void refresh(Tap tap) {
        if (tap != null) {
            taps.put(tap.getId(), tap);
        }
    }

    public synchronized List<Tap> getTaps() {
        List<Tap> taps = new ArrayList<>();
        taps.addAll(this.taps.values());
        return taps;
    }

    public synchronized List<Tap> getLaps() {
        return new ArrayList<>((taps.values()));
    }

    public synchronized TreeMap<Integer, Tap> getTapMap() {
        return taps;
    }

    public synchronized void clear() {
        taps.clear();
    }

    public synchronized void refresh(int tapId, byte[] statusBytes) {
        Tap tap = taps.get(tapId);
        if (tap != null) {
            int status = statusBytes[1] & 0x01;
            LogUtil.e(TAG, "tap is :" + tapId);
            int refreshStatus = status == 0 ? Tap.OFF : Tap.ON;
            if (refreshStatus != tap.getRefreshStatus()) {
                Log.e(TAG, "interval:" + (System.currentTimeMillis() - tap.getControlTime()));
                tap.setRefreshTime(System.currentTimeMillis());
                tap.setRefreshStatus(refreshStatus);
            }
        } else {
            LogUtil.e(TAG, "tap is null:" + tapId);
        }
    }
}
